﻿<?php
class Admin_ClientsController extends My_Controller_Admin_Action
{
	protected $clientsModel = '';

	protected function _init()
	{
		$this->clientsModel = new Admin_Model_Clients();
	}

	public function indexAction()
	{
        $org = $this->_getParam('org', 'all');
        $ordre = $this->_getParam('ordre', 'num_client, nom');
        $tri = $this->_getParam('tri', 'asc');
        
	    $num_vente = $this->_getParam('num_vente');
		$rowPerPage = $this->_getParam('rowperpage', 20);
		$currentPage = 1;
		$page = $this->_getParam('page', 1);
		if(!empty($page)) {
			$currentPage = $page;
		}

        if ($org == "all" || $org == "arc") 
		    $rows = $this->clientsModel->getListClient($num_vente, $org, $ordre, $tri);
        else 
            $rows = $this->clientsModel->getListClientArchived($num_vente, $org, $ordre, $tri);
            
		$paginator = Zend_Paginator::factory($rows);
		$paginator->setItemCountPerPage($rowPerPage);
		$paginator->setCurrentPageNumber($currentPage);

		$this->view->page = $page;
		$this->view->paginator = $paginator;
        $this->view->org = $org;
        $this->view->ordre = $ordre;
        $this->view->tri = $tri;
		$this->view->num_vente = $num_vente;
        
	}
    
	public function addAction()
	{
		$num_vente = $this->_getParam('num_vente', 0);
        $org = $this->_getParam('org', 'all');
		
		$this->view->num_vente = $num_vente;
		$this->view->org = $org;
		$this->view->messages = $this->_helper->flashMessenger->getMessages();
	}
	
	public function editAction()
	{
		$num_vente = $this->_getParam('num_vente', 0);
        $org = $this->_getParam('org', 'all');
		$num = $this->_getParam('num', 0);

		$this->view->num_vente = $num_vente;
		$this->view->org = $org;
		$this->view->num = $num;
		$this->view->messages = $this->_helper->flashMessenger->getMessages();
	}
	
	public function insertClientsAction()
	{
		$num_vente = $this->_getParam('num_vente', 0);
		$num_client = $this->_getParam('num_client', 0);
        $org = $this->_getParam('org', 'all');
		
		$liste = "contact,vendeur,acheteur,identite,email,commission,prenom,nom,adresse,adresse2,cp,ville,pays,tel1,tel2,tel3,tel4,banque,tva,obj,bd,fg";
		// On stocke dans des variables de sessions les valeurs du formulaire pour le remplir dans la page précédente
		$i = explode(",",$liste);
		for ($compt=0; $compt<(count($i)); $compt++) {
			$_SESSION[$i[$compt]] = $_POST[$i[$compt]];
		}
		
		// On vérifie si le n° de client existe déjà dans la DB
		if (!$num_client) {
			$num_client = 'n';
		} else {
			$num_client = sprintf("%04s", $num_client);
		}
		
		if ($num_client != 'n') {
			$count = $this->clientsModel->isClient($num_client, $num_vente);
			if ($count != 0) {
				$mgs  = "Ce n° de client existe déjà !";
				$this->_helper->flashMessenger->addMessage($mgs);
				$this->_redirect('admin/clients/add?num_vente='. $num_vente .'&org='. $org);
			}
		}
		
		$vendeur = $this->_getParam('vendeur', 0);
		$acheteur = $this->_getParam('acheteur', 0);
		$contact = $this->_getParam('contact', 0);
		$nom = addslashes($this->_getParam('nom', ''));
		$co = addslashes($this->_getParam('co', ''));
		$prenom = addslashes($this->_getParam('prenom', ''));
		$adresse = addslashes($this->_getParam('adresse', ''));
		$adresse2 = addslashes($this->_getParam('adresse2', ''));
		$ville = addslashes($this->_getParam('ville', ''));
		$bd = $this->_getParam('bd', 0);
		$obj = $this->_getParam('obj', 0);
		$fg = $this->_getParam('fg', 0);
		$archive = $this->_getParam('archive', 0);
		
		$identite = $this->_getParam('identite', 0);
		$email = $this->_getParam('email', '');
		$pays = $this->_getParam('pays', '');
		$tel1 = $this->_getParam('tel1', '');
		$tel2 = $this->_getParam('tel2', '');
		$tel3 = $this->_getParam('tel3', '');
		$tel4 = $this->_getParam('tel4', '');
		$banque = $this->_getParam('banque', '');
		$tva = $this->_getParam('tva', '');
		$civilite = $this->_getParam('civilite', '');
		$catoffice = $this->_getParam('catoffice', '');
		$contact_depot = $this->_getParam('contact_depot', '');
		$commission = $this->_getParam('commission', '');
		$cp = $this->_getParam('cp', '');

		$cle = $this->clientsModel->getMaxClient();
		$data = array(
			p_clients		=> $cle,
			vendeur			=> $vendeur,
			acheteur		=> $acheteur,
			num_identite	=> $identite,
			email			=> $email,
			prenom			=> $prenom,
			nom				=> $nom,
			adresse			=> $adresse,
			adresse2		=> $adresse2,
			cp				=> $cp,
			ville			=> $ville,
			f_pays			=> $pays,
			tel1			=> $tel1,
			tel2			=> $tel2,
			tel3			=> $tel3,
			tel4			=> $tel4,
			compte_banque	=> $banque,	
			tva				=> $tva,
			dtcreat			=> date('Y-m-d'),
			hrcreat			=> date('his'),
			co				=> $co,
			f_civilites		=> $civilite,
			contact			=> $contact,
			bd				=> $bd,
			obj				=> $obj,
			fg				=> $fg,
			archive			=> $archive,
			catoffice		=> $catoffice,	
			contact_depot	=> $contact_depot
		);
		
		$clientsModel = new Admin_Model_Clients();
		$clientsModel->insert($data);
	
		$i = explode(",",$liste);
		for ($compt=0; $compt<(count($i)); $compt++) {
			unset($_SESSION[$i[$compt]]);
		}

		// Ajout du client pour les prochaines ventes
		if ($commission != "") {
			$com = str_replace(",",".", $commission);
		} else {
			$com = 0; 
		}
		
		$rows = $this->clientsModel->getVentes($num_vente);
		foreach($rows as $row) {
			if ($row['p_ventes'] == $num_vente) {
				$numclient = $numclient;
			} else {
				$numclient = 'n';
			}

			$this->clientsModel->insetClientEvent($cle, $row['p_ventes'], $numclient, $com);
		}
		
		$this->_redirect('admin/clients?num_vente='. $num_vente .'&org='. $org);
	}
	
	public function updateClientAction() 
	{
		$num_vente = $this->_getParam('num_vente', 0);
		$num_client = $this->_getParam('num_client', '');
        $org = $this->_getParam('org', 'all');
		$num = $this->_getParam('num', 0);
		
		$userId = $this->_getParam('userid', '');
		if ($userId != "") {
			$qU = "select p_clients from clients where userid='$userId'";
			$rowU = $this->clientsModel->fecthRowClient($qU);
			$numRow = $this->clientsModel->rowCountClient($qU);
			if ($numRow == 1 && $rowU['p_clients'] != $num) {
				$mgs  = "Ce userid existe déjà dans la DB !";
				$this->_helper->flashMessenger->addMessage($mgs);
				$this->_redirect('admin/clients/edit?num='. $num .'&num_vente='. $num_vente .'&org='. $org);
			}
		}
		
		$email = $this->_getParam('email', '');
		if ($email != "") {
			$qU = "select p_clients from clients where email='$email'";
			$rowU = $this->clientsModel->fecthRowClient($qU);
			$numRow = $this->clientsModel->rowCountClient($qU);
			if ($numRow == 1 && $rowU['p_clients'] != $num) {
				$mgs  = "Cette adresse e-mail existe déjà dans la DB !";
				$this->_helper->flashMessenger->addMessage($mgs);
				$this->_redirect('admin/clients/edit?num='. $num .'&num_vente='. $num_vente .'&org='. $org);
			}		
		}	
		
		// Si on archive le client, on lui retire son n° d'acheteur dans les ventes suivantes
		$archive = $this->_getParam('archive', '');
		if($archive == 1) {
			$this->clientsModel->updateClientVentes($num, $num_vente);
			$num_client = 'n';
		}
		
		if (!$num_client) { $num_client = 'n'; }
		if ($num_client != 'n') {
			$q = "SELECT clients.p_clients, clients.archive FROM clients
			Left Join clients_ventes ON clients.p_clients = clients_ventes.f_clients
			where deleted = 0 and clients_ventes.num_client='". sprintf("%04s",$num_client) ."' and f_ventes = $num_vente";
			
			$row = $this->clientsModel->fecthRowClient($q);
			$numRow = $this->clientsModel->rowCountClient($q);
			
			if ($numRow != 0 && $row['p_clients'] != $num) {
				$mgs  = "Ce n° de client existe déjà !";
				$this->_helper->flashMessenger->addMessage($mgs);
				$this->_redirect('admin/clients/edit?num='. $num .'&num_vente='. $num_vente .'&org='. $org);
			} else {
				$q = "update clients_ventes set num_client = '" . sprintf('%04s',$num_client) . "' where f_clients = $num and f_ventes = $num_vente";
				$this->clientsModel->updateRowClient($q);
			}
		} else {
			$q = "update clients_ventes set num_client = 'n' where f_clients = $num and f_ventes = $num_vente";
			$this->clientsModel->updateRowClient($q);
		}
		
		$vendeur = $this->_getParam('vendeur', 0);
		$acheteur = $this->_getParam('acheteur', 0);
		$contact = $this->_getParam('contact', 0);
		$nom = addslashes($this->_getParam('nom', ''));
		$co = addslashes($this->_getParam('co', ''));
		$prenom = addslashes($this->_getParam('prenom', ''));
		$adresse = addslashes($this->_getParam('adresse', ''));
		$adresse2 = addslashes($this->_getParam('adresse2', ''));
		$ville = addslashes($this->_getParam('ville', ''));
		$bd = $this->_getParam('bd', 0);
		$obj = $this->_getParam('obj', 0);
		$fg = $this->_getParam('fg', 0);
		$archive = $this->_getParam('archive', 0);
		
		$identite = $this->_getParam('identite', 0);
		$email = $this->_getParam('email', '');
		$pays = $this->_getParam('pays', '');
		$tel1 = $this->_getParam('tel1', '');
		$tel2 = $this->_getParam('tel2', '');
		$tel3 = $this->_getParam('tel3', '');
		$tel4 = $this->_getParam('tel4', '');
		$banque = $this->_getParam('banque', '');
		$tva = $this->_getParam('tva', '');
		$civilite = $this->_getParam('civilite', '');
		$catoffice = $this->_getParam('catoffice', '');
		$contact_depot = $this->_getParam('contact_depot', '');
		$commission = $this->_getParam('commission', '');
		$cp = $this->_getParam('cp', '');

		$data = array(
			vendeur			=> $vendeur,
			acheteur		=> $acheteur,
			num_identite	=> $identite,
			email			=> $email,
			prenom			=> $prenom,
			nom				=> $nom,
			adresse			=> $adresse,
			adresse2		=> $adresse2,
			cp				=> $cp,
			ville			=> $ville,
			f_pays			=> $pays,
			tel1			=> $tel1,
			tel2			=> $tel2,
			tel3			=> $tel3,
			tel4			=> $tel4,
			compte_banque	=> $banque,	
			tva				=> $tva,
			dtcreat			=> date('Y-m-d'),
			hrcreat			=> date('His'),
			co				=> $co,
			f_civilites		=> $civilite,
			contact			=> $contact,
			bd				=> $bd,
			obj				=> $obj,
			fg				=> $fg,
			userid			=> $userId,
			archive			=> $archive,
			catoffice		=> $catoffice,	
			contact_depot	=> $contact_depot
		);
		
		$clientsModel = new Admin_Model_Clients();
		$clientsModel->update($data, 'p_clients = ' . $num);

		
		$valid = $this->_getParam('valid', '');
		// On vérifie s'il faut valider cet utilisateur
		if (isset($valid) && $valid == 1) {
			//$q = "update clients set dtvalid = '$ladate',hrvalid='$lheure',validated=1,acheteur=1 where p_clients = $_GET[num]";	
			$q = "update clients set dtvalid = '". date('Y-m-d') ."',hrvalid='" . date('His') ."',validated=1 where p_clients = $num";	
			$this->clientsModel->updateRowClient($q);
			//include("_mail_confirm_validation.php");
		}
			// On vérifie s'il faut retirer la validation de cet utilisateur
		if (isset($valid) && $valid == '19000101') {
			$q = "update clients set dtvalid=null,hrvalid=null,validated=0 where p_clients = $num";	
			$this->clientsModel->updateRowClient($q);
		}

		// Ajout dans la table clients_ventes si n° d'acheteur présent ou possède des articles en vente
		// Vérification de la présence d'articles
		$q = "select p_articles from articles where f_clients_deposant = $_GET[num]";
		$numRow = $this->clientsModel->rowCountClient($q);

		if ($num_client != 'n' || $numRow > 0) {
			$q = "delete from clients_ventes where f_clients = $num and f_ventes = $num_vente]";
			$this->clientsModel->updateRowClient($q);
			$commission = str_replace(",",".",$commission);
			$q = "insert into clients_ventes (f_clients,f_ventes,num_client,commission) values ($num,$num_vente,'$num_client',$commission)";
			$this->clientsModel->updateRowClient($q);
		}

		// Zone commission
		//echo "com : " .$_POST[commission]."<br>";
		if ($commission != "") {
			$commission = str_replace(",",".",$commission);
			$q_comm = "update clients_ventes set commission = $commission where f_clients = $num and f_ventes = $num_vente";
			$this->clientsModel->updateRowClient($q_comm);
		}

		$this->_redirect('admin/clients?num_vente='. $num_vente .'&org='. $org ."#$num");
	}
	
    public function deleteAction()
    {
        $num = $this->_getParam('num');
        $num_vente = $this->_getParam('num_vente');
        $page = $this->_getParam('page', 1);
        $org = $this->_getParam('org', 'all');
        $this->clientsModel->removeClient($num, $num_vente);

        $param = '';
        if($page > 1) $param = '&page=' . $page;
        $this->_redirect('admin/clients?num_vente='. $num_vente .'&org='. $org . $param);
    }
	
	public function searchEmailAction()
	{
		$btnSearch = $this->_getParam('btnSearch', '');
		$org = $this->_getParam('org', 'all');
		$num_vente = $this->_getParam('num_vente', 0);
		$email = $this->_getParam('lemail', '');
		
		if($btnSearch) {
			$row = $this->clientsModel->getCLientsByEmail($email);

			if($row['p_clients']) {
				$this->_redirect('admin/clients/add?num='. $row['p_clients'] .'&num_vente='. $num_vente .'&org='. $org);
			} else {
				$msg = "Cette adresse n'a pas été trouvée !";
				$this->view->msg = $msg;
			}
		}
		
		$this->view->org = $org;
        $this->view->num_vente = $num_vente;
	}
	
	public function ficheClientPdfAction()
	{
	
	}
}

